package com.sharer.last.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sharer.last.base.enums.BusinessExceptionCode;
import com.sharer.last.base.enums.ExceptionPrefixParamEnum;
import com.sharer.last.base.exception.BusinessException;
import com.sharer.last.mapper.UserMapper;
import com.sharer.last.model.dto.user.UserUpdateDTO;
import com.sharer.last.model.po.UserPO;
import com.sharer.last.service.UserService;
import com.sharer.last.utils.BeanUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户业务层接口实现类
 *
 * @ClassName UserServiceImpl
 * @Author wangjin
 * @Date 2023/5/5 20:46
 * @Description
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService, UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    BCryptPasswordEncoder passwordEncoder;

    /**
     * 根据用户名称获取用户信息
     *
     * @param username 用户名称
     * @return
     */
    @Override
    public UserPO getByUserName(String username) {
        LambdaQueryWrapper<UserPO> qw = new LambdaQueryWrapper<>();
        qw.eq(UserPO::getUsername, username);
        return this.getOne(qw, false);
    }

    /**
     * 根据用户名获取用户信息 Security
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPO user = getByUserName(username);
        if (user == null) {
            throw new BusinessException(BusinessExceptionCode.DATA_IS_EMPTY, ExceptionPrefixParamEnum.USER);
        }
        return user;
    }

    /**
     * 修改密码或昵称
     *
     * @param user
     */
    @Override
    public void updateAccount(UserUpdateDTO user) {
        String pwd    = passwordEncoder.encode(user.getPassword());
        UserPO userPO = BeanUtil.copy(user, UserPO.class);
        userPO.setPassword(pwd);
        if (!this.updateById(userPO)) {
            throw new BusinessException(BusinessExceptionCode.DATA_UPDATE_FAIL, ExceptionPrefixParamEnum.USER);
        }
    }
}
